/*
   (C) 2007 - Michael Ocean - Boston University

  This work is a part of the larger snBench project.  Information
  can be found at: http://csr.bu.edu/snbench

  This program is free software; you can redistribute it and/or
  modify it under the terms of Version 2 of the GNU General Public 
  License.
  
  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.
  
  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package sxe.sensors;

import snobject.snNil;
import snobject.snObject;
import sxe.sensors.KismetClient.msgtypes;

public class KismetSensor extends GenericSensor {

	private KismetClient kc = null;
	private String host;
	private int port;
	private String location;
	private String mode;
	
	/** no one should call this constructor other than the Parser for use by the SSD/SRM!! */
	protected KismetSensor(){
		super();
	}

	
	public KismetSensor(String host, int port, String mode, String id, String location ) {
		//super();
		m_state = STATE_PREINIT;
		m_type = TYPE_KISMET;

		this.host = host;
		this.port = port;
		super.m_id = id;
		this.location = location;
		this.mode = mode;
		
		// m_uri = HOST + PREFIX + TYPE + ID;
		super.m_uri = m_type + "/" + m_id;
		SensorDetector.RegisterID(m_id);
	}

	public boolean initializeSensor() {	
		try{
			kc = new KismetClient(host,port,super.m_id);
			kc.setMode(mode);
			m_state = STATE_INIT;
			return true;
		}
		catch(Exception e){
			kc = null;
			//e.printStackTrace();
			m_state = STATE_FAILED;
			return false;
		}
	}

	public boolean shutDown() {
		if(kc!=null){
			kc.disconnect();
			super.m_state = STATE_PREINIT;
			return true;
		}
		super.m_state = STATE_FAILED;
		return false;
	}
	
	public String GetInfoXML() {
		// put specific info here
		String s = new String("<location>" + location + "</location>");
		
		return super.GetInfoXML(s);
	}

	/**
	 * return a single snStruct of the KismetMessage 
	 */
	public snObject getData(Object oParam) {
		// Notice: Only one object is retrieved.  Buffer may over run...
		if(kc==null)
			return snNil.NIL;
		
		KismetMessage km = null;
		
		if(KismetClient.msgtypes.parse(mode).equals(msgtypes.ACTIVITY)){
			if(oParam == null)
				return kc.GetAllActivity();
			km = kc.Find((String)oParam);	
		}
		else
			km = kc.GetOldestReading(); //kc.GetNewestReading();
		
		if(km==null)
			return snNil.NIL;

		return km.getSnObject();
	}

	public boolean isAlive() {
		return kc.isConnected();
	}

}
